/********************************************
 * 功能说明: TenantEmployee实体对应的业务逻辑Service实现类
 * 模块名称:
 * 系统名称:
 * 软件版权: Frank
 * 系统版本: 1.0.0.1
 * 开发人员:
 * 开发时间: 2019-12-18 18:41:08
 * 审核人员:
 * 相关文档:
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.uaa.service;

import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.uaa.enums.Constant;
import com.spring.arch.uaa.errorcode.UaaErrorCode;
import com.spring.arch.uaa.model.*;
import com.spring.arch.uaa.repository.UserRepository;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.uaa.model.*;
import com.spring.arch.uaa.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.Optional;
import java.util.UUID;

import static com.spring.arch.uaa.enums.Constant.PROJECT_ADMIN_CODE_PREFIX;
import static com.spring.arch.uaa.errorcode.UaaErrorCode.*;


/**
 * TenantEmployee实体对应的业务逻辑Service实现类
 *
 * @author
 * @version 1.0.0.1
 * @since 2019-12-18 18:41:08
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TenantEmployeeService {

    @Autowired
    private TenantEmployeeRepository tenantEmployeeRepository;
    @Autowired
    private OrganizationEmployeeRepository organizationEmployeeRepository;
    @Autowired
    private OrganizationEmployeeRoleRepository organizationEmployeeRoleRepository;
    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRepository userRepository;

    public TenantEmployee save(TenantEmployee model, UUID projectId) {
        @NotNull Tenant tenant = model.getTenant();
        // 校验员工编号、手机号
        boolean existsCode, existsMobile;
        if(model.isNew()) {
            existsCode = tenantEmployeeRepository.existsByCodeAndTenant(model.getCode(), tenant);

            if(model.getCode().startsWith(Constant.PROJECT_ADMIN_CODE_PREFIX)) {
                existsMobile = tenantEmployeeRepository.existsByMobileAndTenantAndCodeNotLike(model.getMobile(), tenant,
                        Constant.PROJECT_ADMIN_CODE_PREFIX + "%");
            } else {
                existsMobile = tenantEmployeeRepository.existsByMobileAndTenant(model.getMobile(), tenant);
            }
        } else {
            existsCode = tenantEmployeeRepository.existsByCodeAndTenantAndIdNot(model.getCode(), tenant, model.getId());

            if(model.getCode().startsWith(Constant.PROJECT_ADMIN_CODE_PREFIX)) {
                existsMobile = tenantEmployeeRepository.existsByMobileAndTenantAndIdNotAndCodeNotLike(model.getMobile(),
                        tenant, model.getId(), Constant.PROJECT_ADMIN_CODE_PREFIX + "%");
            } else {
                existsMobile = tenantEmployeeRepository.existsByMobileAndTenantAndIdNot(model.getMobile(), tenant, model.getId());
            }

            if(!model.isStatus()) {
                organizationEmployeeRoleRepository.deleteAllByOrganizationEmployeeEmployeeId(model.getId());
                organizationEmployeeRepository.deleteByEmployeeId(model.getId());
            }
        }
        if(existsCode) {
            throw ExceptionHolder.serviceException(UaaErrorCode.E2001004004, model.getCode());
        }

        if(existsMobile) {
            throw ExceptionHolder.serviceException(UaaErrorCode.E2001004003, model.getMobile());
        }

        UUID id = model.getId();
        model = tenantEmployeeRepository.save(model);

        if(id == null && projectId != null) {
            Project project = projectRepository.findById(projectId).orElseThrow(
                    () -> ExceptionHolder.serviceException(UaaErrorCode.E2001002001, String.valueOf(projectId)));

            User user = userService.createUser(model);

            OrganizationEmployee projctEmployee = new OrganizationEmployee();
            projctEmployee.setOrganization(project.getRootOrganization());
            projctEmployee.setEmployee(model);
            projctEmployee.setUser(user);

            organizationEmployeeRepository.save(projctEmployee);
        }

        if(!model.isNew()) {

            Optional<User> optionalUser = userRepository.findByMobile(model.getMobile());
            if(optionalUser.isPresent()){
                User user = optionalUser.get();
                user.setRealName(model.getName());
                user.setEmail(model.getEmail());
                user.setGender(model.getGender());
                userService.save(user);
            }
        }

        return model;
    }

    public void deleteById(UUID id) {
        TenantEmployee employee = tenantEmployeeRepository.findById(id)
                .orElseThrow(() -> ExceptionHolder.serviceException(UaaErrorCode.E2001001002, String.valueOf(id)));

        this.organizationEmployeeRoleRepository.deleteAllByOrganizationEmployeeEmployeeId(id);
        this.organizationEmployeeRepository.deleteByEmployeeId(id);

        employee.setDisable(true);
        this.tenantEmployeeRepository.save(employee);
    }
}
